import { computed } from 'vue'
import { useStore } from 'vuex'

export const useCartEffect = (shopId) => {
  const store = useStore()
  const cartList = store.state.cartList
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    store.commit('addItemToCart', { shopId, productId, productInfo, num })
  }
  const calculations = computed(() => {
    const result = {
      total: 0,
      totalPrice: 0,
      allChecked: 0,
      productData: cartList[shopId]?.productList || {},
      shopName: cartList[shopId]?.shopName || '',
      notEmptyProductList: {}
    }
    for (const i in result.productData) {
      const product = result.productData[i]
      result.total += product.count
      if (product.checked) {
        result.totalPrice += product.count * product.price
      }
      if (product.count > 0 && !product.checked) {
        result.allChecked = false
      }
      for (const i in result.productData) {
        const product = result.productData[i]
        if (product.count > 0) {
          result.notEmptyProductList[i] = product
        }
      }
    }

    result.totalPrice = result.totalPrice.toFixed(2)
    return result
  })
  return { cartList, changeCartItemInfo, calculations }
}
